import csv
import os
from datetime import datetime
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class ExportManager:
    def __init__(self, db_manager):
        self.db_manager = db_manager
        
    def export_to_csv(self, file_path=None):
        #将票据数据导出到CSV文件
        # 如果未指定路径，使用默认路径和文件名
        if not file_path:
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            file_path = f'tickets_export_{timestamp}.csv'
        
        try:
            # 查询所有票据数据
            sql = "SELECT * FROM tickets ORDER BY created_at DESC"
            tickets = self.db_manager.execute_query(sql)
            
            if not tickets:
                logger.warning('没有找到票据数据')
                return False, '没有找到票据数据'
            
            # 写入CSV文件
            with open(file_path, 'w', newline='', encoding='utf-8') as csvfile:
                fieldnames = tickets[0].keys()
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                
                writer.writeheader()
                for ticket in tickets:
                    writer.writerow(ticket)
            
            logger.info(f'票据数据已成功导出到: {file_path}')
            return True, f'票据数据已成功导出到: {file_path}'
        except Exception as e:
            logger.error(f'导出CSV失败: {str(e)}')
            return False, f'导出失败: {str(e)}'